//
//  PhotoCameraViewController.m
//  XPhoto
//
//  Created by baboy on 2019/6/4.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "PhotoCameraViewController.h"
#import "Theme.h"
#import <Photos/Photos.h>
#import "PHAsset+x.h"
#import "PhotoEditViewController.h"
#import "PhotoAsset.h"
#import "UIImage+x.h"


@interface PhotoCameraViewController ()
@property(nonatomic, strong) NSMutableArray *previewImageViews;
@end

@implementation PhotoCameraViewController
- (id)init{
    if (self = [super init]) {
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    DLOG(@"viewDidLoad:%@,%@", NSStringFromCGRect(self.imagePickerController.cameraOverlayView.frame), NSStringFromCGRect(self.view.frame));
    self.delegate = self;
    self.photoAssets = [NSMutableArray array];
    self.previewImageViews = [NSMutableArray array];
    
    
    // Do any additional setup after loading the view from its nib.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    DLOG(@"viewWillAppear:%@", NSStringFromCGRect(self.view.frame));
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    DLOG(@"viewDidAppear:%@", NSStringFromCGRect(self.view.frame));
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    DLOG(@"viewDidLayoutSubviews:%@", NSStringFromCGRect(self.view.frame));
}
- (void)loadOverlayView{
    self.overlayView =  [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([PhotoCameraOverlayView class])
                                                      owner:self
                                                    options:nil][0];
    self.overlayView.delegate = self;
    self.overlayView.frame = self.view.bounds;
    self.cameraOverlayView = self.overlayView;
    
}
#pragma button actions
- (void) removePhoto:(NSInteger)index{
    [self.photoAssets removeObjectAtIndex:index];
    UIView *v = [self.previewImageViews objectAtIndex:index];
    [v removeFromSuperview];
    [self.previewImageViews removeObjectAtIndex:index];
}
- (void) addPhoto:(PhotoAsset *)photoAsset{
    [self.photoAssets addObject:photoAsset];
    
    
    CGRect frame = CGRectMake(0, 0, 40, 40);
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
//    [photoAsset.asset loadLowQualityImageWithTargetSize:frame.size
//                             progressHandler:^(double progress, NSError * _Nonnull error, BOOL * _Nonnull stop, NSDictionary * _Nonnull info) {
//
//                             }
//                               resultHandler:^(UIImage * _Nonnull result, NSDictionary * _Nonnull info) {
//                                   imageView.image = result;
//                               }];
    imageView.image = photoAsset.thumbImage;
    [self.overlayView.previewButton setImage:photoAsset.thumbImage forState:UIControlStateNormal];
    [self.overlayView.previewContainer addSubview:imageView];
    [self.previewImageViews addObject:imageView];
    
    
    CGRect previewButtonFrame = self.overlayView.previewButton.frame;
    NSString *num = [NSString stringWithFormat:@"%ld",self.photoAssets.count];
    CGSize numSize = [num sizeWithAttributes:@{NSFontAttributeName:self.overlayView.photoCountLabel.font}];
    CGRect labelFrame = CGRectMake(previewButtonFrame.origin.x+previewButtonFrame.size.width - numSize.width - 2, previewButtonFrame.origin.y-5, numSize.width+4, numSize.height+4);
    labelFrame.size.width = MAX(labelFrame.size.width, labelFrame.size.height );
    self.overlayView.photoCountLabel.frame = labelFrame;
    self.overlayView.photoCountLabel.text = num;
    self.overlayView.photoCountLabel.layer.cornerRadius = labelFrame.size.height/2;
    self.overlayView.photoCountLabel.hidden = self.photoAssets.count==0;
    self.overlayView.previewButton.hidden = self.photoAssets.count==0;
    
    [self relayoutPreviewImageView];
}
- (void) relayoutPreviewImageView{
    CGFloat ITEM_MARGIN = 5;
    CGRect itemFrame = CGRectMake(ITEM_MARGIN, ITEM_MARGIN, 50, 50);
    for (NSInteger i = 0; i<self.previewImageViews.count; i++) {
        UIImageView *imageView = [self.previewImageViews objectAtIndex:i];
        imageView.frame = itemFrame;
        itemFrame.origin.x += itemFrame.size.width + ITEM_MARGIN;
    }
    self.overlayView.previewContainer.contentSize = CGSizeMake(self.previewImageViews.count*(itemFrame.size.width+ITEM_MARGIN), 0);
}
#pragma picker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey, id> *)info{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    NSData *thumbData = UIImageJPEGRepresentation(image, 0.1);
    DLOG(@"didFinishPickingMediaWithInfo， thumb size:%ld", [thumbData length]);
    UIImage *thumbImage = [UIImage imageWithData:thumbData];
    PhotoAsset *photoAsset = [[PhotoAsset alloc] initWithAsset:nil thumbnail:thumbImage];
    [self addPhoto:photoAsset];
    [BKIndicator showTips:NSLocalizedString(@"handling", @"提示")
                  offsetY:self.overlayView.bounds.size.height - self.overlayView.bottomPannel.bounds.size.height
                   inView:self.overlayView
                 duration:5.0f
               completion:nil];
    
    NSError *error = nil;
    __block PHObjectPlaceholder *createdAsset = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        PHAssetChangeRequest *request = [PHAssetCreationRequest creationRequestForAssetFromImage:image];
        createdAsset = request.placeholderForCreatedAsset;
    } error:&error];
    PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[createdAsset.localIdentifier] options:nil];
    if (result && result.count>0) {
        PHAsset *asset = [result objectAtIndex:0];
        photoAsset.asset = asset;
    }
}
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    DLOG(@"4:%@,%@",error, contextInfo);
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    DLOG(@"3");
    
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
//    self.imagePickerController.cameraOverlayView = self.view;
    [self loadOverlayView];
}
#pragma overlayView delegate

- (void)overlayView:(id)view clickTakePhotoButton:(id)button{
    [self takePicture];
}
- (void)overlayView:(id)view clickDeviceButton:(id)button{
    
    if (self.cameraDevice == UIImagePickerControllerCameraDeviceRear) {
        self.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }else{
        self.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    }
}
- (void)overlayView:(id)view clickCancelButton:(id)button{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)overlayView:(id)view clickNextButton:(id)button{
    NSMutableArray *assets = [NSMutableArray array];
    for (NSInteger i = 0; i<self.photoAssets.count; i++) {
        PhotoAsset *photoAsset = [self.photoAssets objectAtIndex:i];
        [assets addObject:photoAsset.asset];
    }
    if (assets.count == 0) {
        return;
    }
    if (self.edit) {
        PhotoEditViewController *photoEditViewController = [[PhotoEditViewController alloc] initWithPhotos:self.photoAssets];
        photoEditViewController.delegate = self.photoEditDelegate;
        [self pushViewController:photoEditViewController animated:YES];
        return;
    }
    
}
- (void)overlayView:(id)view clickPreviewButton:(id)button{
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

+ (PhotoCameraViewController *)imagePickerControllerForTakePicture{
    UIImagePickerController *picker = [[PhotoCameraViewController alloc] init];
    [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
    NSLog(@"imagePickerControllerForTakePicture1:%@", NSStringFromCGRect(picker.cameraOverlayView.frame));
    picker.showsCameraControls = NO;
    picker.navigationBarHidden = YES;
    picker.edgesForExtendedLayout = UIRectEdgeNone;
    
    
    CGSize screenBounds = [UIScreen mainScreen].bounds.size;
    CGFloat cameraAspectRatio = 4.0f/3.0f;
    CGFloat camViewHeight = screenBounds.width * cameraAspectRatio;
    CGFloat scale = screenBounds.height / camViewHeight;
    picker.cameraViewTransform = CGAffineTransformMakeTranslation(0, (screenBounds.height - camViewHeight) / 2.0);
    picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, scale, scale);
    
    picker.mediaTypes = @[(NSString*)kUTTypeImage];
    for (NSString *mediaType in picker.mediaTypes) {
        if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
            [picker setVideoMaximumDuration:180];
        }
    }
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        picker.videoQuality = UIImagePickerControllerQualityTypeMedium;
    }
    
    
    return picker;
}
+ (PhotoCameraViewController *)imagePickerControllerForShootVideo{
//    UIImagePickerController *picker = [[PhotoCameraViewController alloc] init];
//    [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
//    picker.showsCameraControls = NO;
//    picker.mediaTypes = @[(NSString*)kUTTypeMovie];
//    for (NSString *mediaType in picker.mediaTypes) {
//        if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
//            [picker setVideoMaximumDuration:180];
//        }
//    }
//    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
//        picker.videoQuality = UIImagePickerControllerQualityTypeMedium;
//    }
//    PhotoCameraViewController *overlayViewController = [[PhotoCameraViewController alloc] init];
//    overlayViewController.imagePickerController = picker;
//    picker.cameraOverlayView = overlayViewController.view;
//    return overlayViewController;
    
    PhotoCameraViewController *picker = [[PhotoCameraViewController alloc] init];
    [picker setSourceType:UIImagePickerControllerSourceTypeCamera];
    picker.showsCameraControls = NO;
    picker.navigationBarHidden = YES;
    picker.edgesForExtendedLayout = UIRectEdgeNone;
    
    
    CGSize screenBounds = [UIScreen mainScreen].bounds.size;
    CGFloat cameraAspectRatio = 4.0f/3.0f;
    CGFloat camViewHeight = screenBounds.width * cameraAspectRatio;
    CGFloat scale = screenBounds.height / camViewHeight;
    picker.cameraViewTransform = CGAffineTransformMakeTranslation(0, (screenBounds.height - camViewHeight) / 2.0);
    picker.cameraViewTransform = CGAffineTransformScale(picker.cameraViewTransform, scale, scale);
    
    picker.mediaTypes = @[(NSString*)kUTTypeMovie];
    for (NSString *mediaType in picker.mediaTypes) {
        if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]){
            [picker setVideoMaximumDuration:180];
        }
    }
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        picker.videoQuality = UIImagePickerControllerQualityTypeMedium;
    }
    
    
    return picker;
}
@end
